#!/usr/bin/env python3
"""
Conda-aware startup script for AI-Powered SSH Terminal
Checks conda environment and provides setup guidance
"""

import os
import sys
import subprocess
import platform
from pathlib import Path

def check_conda_environment():
    """Check if we're running in the correct conda environment"""
    conda_env = os.environ.get('CONDA_DEFAULT_ENV')
    conda_prefix = os.environ.get('CONDA_PREFIX')
    
    if not conda_env or not conda_prefix:
        return False, "Not running in a conda environment"
    
    if conda_env != 'ai-terminal':
        return False, f"Running in wrong environment: {conda_env} (expected: ai-terminal)"
    
    return True, f"Running in correct environment: {conda_env}"

def check_conda_installation():
    """Check if conda is installed"""
    try:
        result = subprocess.run(['conda', '--version'], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            return True, result.stdout.strip()
        else:
            return False, "Conda command failed"
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False, "Conda not found in PATH"

def get_setup_instructions():
    """Get platform-specific setup instructions"""
    system = platform.system()
    
    if system == "Windows":
        script_name = "setup_conda.bat"
        activate_cmd = "conda activate ai-terminal"
    else:
        script_name = "setup_conda.sh"
        activate_cmd = "conda activate ai-terminal"
    
    return f"""
🔧 Environment Setup Required

1. Create the conda environment:
   {script_name}

2. Or manually:
   conda env create -f environment.yml
   
3. Activate the environment:
   {activate_cmd}
   
4. Then run this script again:
   python start_with_conda.py

📁 Make sure you're in the project directory: {Path(__file__).parent}
"""

def main():
    """Main startup function with conda environment checks"""
    print("🤖 AI-Powered SSH Terminal (Conda Edition)")
    print("=" * 50)
    
    # Check conda installation
    conda_installed, conda_version = check_conda_installation()
    if not conda_installed:
        print(f"❌ Conda not found: {conda_version}")
        print("\n📦 Please install Miniconda or Anaconda:")
        print("   https://docs.conda.io/en/latest/miniconda.html")
        return 1
    
    print(f"✓ Conda found: {conda_version}")
    
    # Check environment
    env_correct, env_msg = check_conda_environment()
    print(f"{'✓' if env_correct else '❌'} Environment: {env_msg}")
    
    if not env_correct:
        print(get_setup_instructions())
        return 1
    
    # Environment is correct, proceed with normal startup
    print("\n✅ Conda environment is correctly configured!")
    print(f"📍 Environment path: {os.environ.get('CONDA_PREFIX')}")
    
    # Import and run the normal startup
    try:
        # Add current directory to path for imports
        sys.path.insert(0, str(Path(__file__).parent))
        
        # Import the main startup module
        from start_server import main as start_main
        
        print("\n🚀 Starting server with conda environment...")
        return start_main()
        
    except ImportError as e:
        print(f"\n❌ Import error: {e}")
        print("\n💡 Try installing missing dependencies:")
        print("   conda activate ai-terminal")
        print("   pip install -r requirements.txt")
        return 1
    except Exception as e:
        print(f"\n❌ Startup error: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())